package servlet;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.print.DocFlavor.INPUT_STREAM;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/download")
public class DownloadServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String fileName = req.getParameter("fileName");
		String filePath = getServletContext().getRealPath("/download/" + fileName);
		//设置文件类型MIME
		String mimeType = getServletContext().getMimeType(fileName);
		System.out.println(mimeType);
		resp.setContentType(mimeType);
		//设置响应头,告诉浏览器，以附件形式下载，而不是解析展示
		resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		
		//读取文件
		InputStream inputStream = new FileInputStream(filePath);
		//获取输出流：通过Response获得输出流，用于向客户端向浏览器输出
		OutputStream outputStream = resp.getOutputStream();
		byte[] buffer = new byte[1024];
		int length = 100;
		while ((length = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer,0,length);
		}
		outputStream.close();
		inputStream.close();
	}
}
